package com.mantru.iotpot.setting;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.R;
import com.mantru.iotpot.setting.Adapter.CalibrateNunberKeyAdapter;

import java.util.ArrayList;
import java.util.List;

public class calibrateActivity extends AppCompatActivity implements CalibrateNunberKeyAdapter.OnCalibrateNumberClickListener, View.OnClickListener {
    private ApplicationClass ac;
    private GridView numberkey;
    private LinearLayout back;
    private TextView name;
    private ImageView img1,img2,img3,img4,img5,img6,img7;
    private ImageView[] imgs;//存储进度图片的数组
    private TextView star1,star2,star3,star4,star5,star6,star7;
    private TextView[] stars;//存储状态的数组
    private TextView num_text;
    private Button confirm;
    private Button put;
    private LinearLayout box;
    private int index = 1;//第n次，共7次，从1-7
    private String nozzle_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calibrate);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        initialization();
        nozzle_name = getIntent().getStringExtra("nozzle_name");
        name.setText(nozzle_name);
        setNumberKey();
    }

    //一个用于设置数字键盘的方法
    private void setNumberKey(){
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            items.add(String.valueOf(i));
        }
        items.add("."); // 小数点
        items.add("0");
        items.add("删除"); // 删除键
        CalibrateNunberKeyAdapter adapter = new CalibrateNunberKeyAdapter(this,items,this);
        numberkey.setAdapter(adapter);
    }

    //初始化控件
    private void initialization(){
        box = findViewById(R.id.calibration_number_key_box);
        back = findViewById(R.id.calibration_back);//返回按钮
        name = findViewById(R.id.calibration_food_name);
        img1 = findViewById(R.id.calibration_img1);
        img2 = findViewById(R.id.calibration_img2);
        img3 = findViewById(R.id.calibration_img3);
        img4 = findViewById(R.id.calibration_img4);
        img5 = findViewById(R.id.calibration_img5);
        img6 = findViewById(R.id.calibration_img6);
        img7 = findViewById(R.id.calibration_img7);
        imgs = new ImageView[]{img1,img2,img3,img4,img5,img6,img7};

        star1 = findViewById(R.id.calibration_star1);
        star2 = findViewById(R.id.calibration_star2);
        star3 = findViewById(R.id.calibration_star3);
        star4 = findViewById(R.id.calibration_star4);
        star5 = findViewById(R.id.calibration_star5);
        star6 = findViewById(R.id.calibration_star6);
        star7 = findViewById(R.id.calibration_star7);
        stars = new TextView[]{star1,star2,star3,star4,star5,star6,star7};

        //初始化小键盘
        num_text = findViewById(R.id.calibration_number_text);
        numberkey = findViewById(R.id.calibration_gridview3);
        confirm = findViewById(R.id.calibration_confirm);//确认按钮
        put = findViewById(R.id.calibration_put);//开始投料按钮
        back.setOnClickListener(this);
        confirm.setOnClickListener(this);
        put.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.calibration_back){//点击返回按钮
            finish();
        } else if (v.getId() == R.id.calibration_confirm) {//点击确认按钮
            if (index != 7){
                String date = num_text.getText().toString();
                float value = parseAndRoundToOneDecimalPlace(date);
                ac.Calibration_Control_Weight(value);//保存重量
                imgs[index-1].setImageResource(R.drawable.finish);
                stars[index - 1].setText("已完成");
                Log.d("calibrateActivity","value: " + value);
                box.setVisibility(View.GONE);
                put.setOnClickListener(this);
                put.setBackgroundResource(R.drawable.button12);
                num_text.setText("0");
                index++;
                Log.d("calibrateActivity","index: " + index);
            }else {//投料到第七次的时候
                String date = num_text.getText().toString();
                float value = parseAndRoundToOneDecimalPlace(date);
                ac.Calibration_Control_Weight(value);//保存重量
                imgs[index-1].setImageResource(R.drawable.finish);
                showCalibrateDialog(value);
            }
        } else if (v.getId() == R.id.calibration_put) {//点击开始投料按钮
            ac.Calibration_Control_Spray(index);
            box.setVisibility(View.VISIBLE);
            put.setOnClickListener(null);
            put.setBackgroundResource(R.drawable.calibrate_confirm_ff666699);
            Log.d("calibrateActivity","push");
            stars[index-1].setText("进行中");
        }
    }

    @Override
    public void onNumberClick(String num) {
        String currentValue = num_text.getText().toString();
        Log.d("number", "currentValue: " + currentValue);
        if (num.equals("删除")) {
            if (currentValue.length() > 0) {
//                String newValue = currentValue.substring(0, currentValue.length() - 1);
//                if (newValue.isEmpty()) {
//                    num_text.setText("0"); // 如果删除后为空，设置为 "0"
//                } else {
//                    num_text.setText(newValue);
//                }
                num_text.setText("0");
            }
        } else if (num.equals(".")) { // 检查是否输入小数点
            if (currentValue.equals("0")) {
                Toast.makeText(this, "输入不正确", Toast.LENGTH_SHORT).show();
            } else if (!currentValue.contains(".")) {
                // 如果当前值不包含小数点，则允许输入小数点
                num_text.setText(currentValue + num);
            }
        } else {
            // 如果当前值是 "0"，并且输入的是非零数字，则替换 "0"
            if (currentValue.equals("0")) {
                if (!num.equals("0")) {
                    num_text.setText(num);
                }
            } else {
                num_text.setText(currentValue + num);
            }
        }
    }

    //一个用于将用户输入的数据转换为float类型的方法
    private float parseAndRoundToOneDecimalPlace(String date) {
        if (date == null || date.isEmpty()) {
            return 0.0f; // 如果输入为空，返回0.0f
        }
        try {
            // 将字符串转换为 float
            float value = Float.parseFloat(date);
            // 保留一位小数并四舍五入
            return Math.round(value * 10) / 10.0f;
        } catch (NumberFormatException e) {
            Log.e("calibrateActivity", "Invalid number format: " + date, e);
            return 0.0f; // 如果格式无效，返回0.0f
        }
    }

    // 显示校准对话框的方法
    private void showCalibrateDialog(float date) {
        // 创建对话框
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_calibrate_situation); // 加载对话框布局
        // 获取对话框中的控件
        ImageView imageView = dialog.findViewById(R.id.dailog_calibrate_situation_img); // 使用 dialog.findViewById
        TextView textView = dialog.findViewById(R.id.dailog_calibrate_situation_text); // 使用 dialog.findViewById
        Button button = dialog.findViewById(R.id.dailog_calibrate_situation_back); // 使用 dialog.findViewById
        if (imageView != null && textView != null && button != null) { // 检查是否为 null
            if (date >= 27.0 && date <= 33.0) {
                imageView.setImageResource(R.drawable.set_true);
                textView.setText("校准成功");
            } else {
                imageView.setImageResource(R.drawable.set_false);
                textView.setText("校准失败");
            }
            button.setOnClickListener(v -> {
                dialog.dismiss(); // 关闭对话框
                finish();
            });
        } else {
            Log.e("calibrateActivity", "One or more views in the dialog are null");
        }

        dialog.show(); // 显示对话框

        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
    }
}